import time
import json
import requests
import random
import datetime
import base64
import requests
from hashlib import md5
import base64
from Crypto.Cipher import DES


def gen_captcha_uuid():
    total_string = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
    part = "".join([random.choice(total_string) for i in range(18)])
    ctime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    captcha_uuid = f"{ctime}{part}"
    return captcha_uuid


def register(captcha_uuid):
    res = requests.get(
        url="https://captcha1.fengkongcloud.cn/ca/v1/register",
        params={
            "captchaUuid": captcha_uuid,
            "model": "select",
            "appId": "default",
            "rversion": "1.0.4",
            "sdkver": "1.1.3",
            "callback": f"sm_callback",
            "organization": "xQsKB7v2qSFLFxnvmjdO",
            "channel": "DEFAULT",
            "lang": "zh-cn",
            "data": "{}"
        }
    )

    data_dict = json.loads(res.text.strip("sm_callback").strip("(").strip(")"))
    return data_dict


def image_ocr(file_bytes):
    # 官方示例：面相对象
    res = requests.post(
        url='http://upload.chaojiying.net/Upload/Processing.php',
        data={
            'user': "whatf233",
            'pass2': md5("Hz527603".encode('utf-8')).hexdigest(),
            'codetype': "9501",
            'file_base64': base64.b64encode(file_bytes)
        },
        headers={
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
    )

    res_dict = res.json()
    # {'err_no': 0, 'err_str': 'OK', 'pic_id': '1234612060701120002', 'pic_str': '的,86,73|粉,111,38|菜,40,49|香,198,101', 'md5': 'faac71fc832b2ead01ffb4e813f3be60'}

    # 8.每个字的坐标  {"鸭":(196,85), ...}    target_word_list = ["花","鸭","字"]
    bg_word_dict = {}
    for item in res_dict["pic_str"].split("|"):
        word, x, y = item.split(",")
        bg_word_dict[word] = (int(x), int(y))
    return bg_word_dict


def des_encrypt(data_string, key):
    pad_func = lambda text: text + '\0' * (DES.block_size - (len(text.encode('utf-8')) % DES.block_size))
    aes = DES.new(key.encode('utf-8'), DES.MODE_ECB)
    enc_data = aes.encrypt(pad_func(data_string).encode("utf8"))
    res = base64.b64encode(enc_data).decode('utf-8')
    return res


def run():
    captcha_uuid = gen_captcha_uuid()

    # 注册请求
    data_dict = register(captcha_uuid)

    # 获取图片和识别的文字
    bg_img_url = f'https://castatic.fengkongcloud.cn{data_dict["detail"]["bg"]}'
    char_list = data_dict["detail"]['order']
    rid = data_dict["detail"]['rid']
    print("图上文字验证码：", char_list)

    res = requests.get(url=bg_img_url).content
    ocr_word_dict = image_ocr(res)
    print("识别的验证码：", ocr_word_dict)

    char_list.reverse()
    select_data = []
    for idx, char in enumerate(char_list, 1):
        group = ocr_word_dict.get(char)
        if not group:
            continue
        x, y = group
        real_x = x / 2 / 300
        real_y = y / 2 / 150
        ctime = int((time.time() - random.uniform(idx - 1, idx) * 1000))
        select_data.insert(0, [real_x, real_y, ctime])
        time.sleep(1)

    print("构造点选坐标：", select_data)

    select_data_string = json.dumps(select_data, separators=(',', ':'))
    start_time = select_data[0][-1]
    end_time = int(time.time() * 1000)

    mapping = {
        "mp": ('default', '9cc268c1'),
        "oc": ('DEFAULT', "c2659527"),
        "xy": ('zh-cn', 'b1807581'),
        "jo": ("11", '6d005958'),
        "qd": (select_data_string, '3c9ed5cb'),
        "mu": (select_data_string, "e7e1eb0d"),
        "ww": (str(end_time - start_time), '17a94a08'),
        "nu": ("300", "390aac0d"),
        "dy": ("150", "a9001672"),
        "tb": ("1", '6f5e9847'),
        "en": ("0", "9fc1337f"),
        "kq": ("-1", 'ebee8dcc'),
    }

    verify_dict = {
        "rid": rid,
        "organization": "xQsKB7v2qSFLFxnvmjdO",
        "rversion": "1.0.4",
        "sdkver": "1.1.3",
        "protocol": "180",
        "ostype": "web",
        "callback": "func_callback",
        "act.os": "web_pc",
        "captchaUuid": captcha_uuid
    }
    for k, group in mapping.items():
        data_string, key = group
        enc = des_encrypt(data_string, key)
        verify_dict[k] = enc

    res = requests.get(
        url="https://captcha1.fengkongcloud.cn/ca/v2/fverify",
        params=verify_dict,
        headers={
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
            "Referer": "https://secure.elong.com/",
            "Host": "captcha1.fengkongcloud.cn",
            "Origin": "https://secure.elong.com",

        }
    )
    print("识别结果：", res.text)


if __name__ == '__main__':
    run()
